package com.centaline.androidsalesblog.fragments.entrust;

import android.app.Activity;
import android.content.DialogInterface;
import android.content.Intent;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.AppCompatEditText;
import android.support.v7.widget.AppCompatTextView;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;

import com.android.volley.VolleyError;
import com.centaline.androidsalesblog.R;
import com.centaline.androidsalesblog.activities.entrust.EstateSearchActivity;
import com.centaline.androidsalesblog.activities.entrust.ModifyPhoneActivity;
import com.centaline.androidsalesblog.activities.entrust.MyHouseResourceActivity;
import com.centaline.androidsalesblog.activities.mine.BindingPhoneActivity;
import com.centaline.androidsalesblog.activities.mine.RegisterActivity;
import com.centaline.androidsalesblog.activities.sale.StaffDetailActivity;
import com.centaline.androidsalesblog.api.sale.EstateStaffApi;
import com.centaline.androidsalesblog.api.usercenter.InsertEntrustInfoRequestApi;
import com.centaline.androidsalesblog.base.BaseFragment;
import com.centaline.androidsalesblog.constants.AppConstant;
import com.centaline.androidsalesblog.constants.CommonConstant;
import com.centaline.androidsalesblog.constants.ExtraConstant;
import com.centaline.androidsalesblog.model.databaseobject.StaffDo;
import com.centaline.androidsalesblog.model.databaseobject.UserDo;
import com.centaline.androidsalesblog.model.responseobject.StaffListRo;
import com.centaline.androidsalesblog.model.responseobject.UserCenterRo;
import com.centaline.androidsalesblog.rx.database.RxDataBase;
import com.centaline.androidsalesblog.utils.AnimationUtil;
import com.centanet.framework.interfaces.IResponseListener;
import com.jakewharton.rxbinding.widget.RxTextView;
import com.trello.rxlifecycle.FragmentEvent;

import rx.Observable;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.functions.Func2;
import rx.schedulers.Schedulers;

/**
 * 委托租房
 * Created by Lihq on 16/3/2.
 */
public class EntrustRentFragment extends BaseFragment implements View.OnClickListener {

    private LinearLayout ll_entrust_rent_estate;
    private LinearLayout ll_entrust_rent_contact;
    private LinearLayout ll_entrust_rent_add;
    private LinearLayout ll_entrust_rent_extra;
    private LinearLayout ll_entrust_rent_type;
    private AppCompatEditText aet_entrust_rent_name;
    private AppCompatEditText aet_entrust_rent_area;
    private AppCompatEditText aet_entrust_rent_eprice;
    private AppCompatEditText aet_entrust_rent_supplement;
    private ImageView img_entrust_rent_add_arrow;
    private AppCompatTextView atv_entrust_rent_estate;
    private AppCompatTextView atv_entrust_rent_phone;
    private AppCompatTextView atv_entrust_rent_type;
    private Button bt_entrust_rent_submit;
    private String cestName;
    private String phone;

    private InsertEntrustInfoRequestApi insertEntrustInfoRequestApi;
    private EstateStaffApi estateStaffApi;
    private boolean flag = false;
    String[] type_arr = new String[]{"一室", "两室", "三室", "四室", "五室", "五室以上",};
    public static final int REQUSET_PHONE = 1;
    public static final int REQUSET_ESTATE = 2;

    private Observable<CharSequence> estateChangeObservable;
    private Observable<CharSequence> phoneChangeObservable;
    private UserDo userdo;
    private StaffDo staffDo;
    private String cestCode;
    private int room;
    private String userPhone;


    @Override
    protected int setLayoutId() {
        return R.layout.fragment_entrust_rent;
    }

    @Override
    protected void findViews(View view) {
        ll_entrust_rent_estate = (LinearLayout) view.findViewById(R.id.ll_entrust_rent_estate);
        ll_entrust_rent_contact = (LinearLayout) view.findViewById(R.id.ll_entrust_rent_contact);
        ll_entrust_rent_add = (LinearLayout) view.findViewById(R.id.ll_entrust_rent_add);
        ll_entrust_rent_extra = (LinearLayout) view.findViewById(R.id.ll_entrust_rent_extra);
        ll_entrust_rent_type = (LinearLayout) view.findViewById(R.id.ll_entrust_rent_type);
        aet_entrust_rent_name = (AppCompatEditText) view.findViewById(R.id.aet_entrust_rent_name);
        aet_entrust_rent_area = (AppCompatEditText) view.findViewById(R.id.aet_entrust_rent_area);
        aet_entrust_rent_eprice = (AppCompatEditText) view.findViewById(R.id.aet_entrust_rent_eprice);
        aet_entrust_rent_supplement = (AppCompatEditText) view.findViewById(R.id.aet_entrust_rent_supplement);
        img_entrust_rent_add_arrow = (ImageView) view.findViewById(R.id.img_entrust_rent_add_arrow);
        atv_entrust_rent_estate = (AppCompatTextView) view.findViewById(R.id.atv_entrust_rent_estate);
        atv_entrust_rent_phone = (AppCompatTextView) view.findViewById(R.id.atv_entrust_rent_phone);
        atv_entrust_rent_type = (AppCompatTextView) view.findViewById(R.id.atv_entrust_rent_type);
        bt_entrust_rent_submit = (Button) view.findViewById(R.id.bt_entrust_rent_submit);

    }

    @Override
    protected void initView() {
        ll_entrust_rent_estate.setOnClickListener(this);
        ll_entrust_rent_contact.setOnClickListener(this);
        ll_entrust_rent_add.setOnClickListener(this);
        ll_entrust_rent_type.setOnClickListener(this);
        bt_entrust_rent_submit.setOnClickListener(this);
        userInfo();

        estateChangeObservable = RxTextView.textChanges(atv_entrust_rent_estate);
        phoneChangeObservable = RxTextView.textChanges(atv_entrust_rent_phone);

        Observable.combineLatest(estateChangeObservable, phoneChangeObservable,
                new Func2<CharSequence, CharSequence, Boolean>() {
                    @Override
                    public Boolean call(CharSequence estateName, CharSequence phoneNumber) {
                        final boolean phoneValid = phoneNumber.length() == 11 &&
                                "1".equals(String.valueOf(phoneNumber.charAt(0)));
                        final boolean estateValid = estateName.toString().equals(cestName);
                        return phoneValid && estateValid;
                    }
                })
                .compose(this.<Boolean>bindUntilEvent(FragmentEvent.DESTROY))
                .subscribe(new Action1<Boolean>() {
                    @Override
                    public void call(Boolean aBoolean) {
                        bt_entrust_rent_submit.setEnabled(aBoolean);
                    }
                });

        if (insertEntrustInfoRequestApi == null) {
            insertEntrustInfoRequestApi = new InsertEntrustInfoRequestApi(RegisterActivity.class, UserCenterRo.class, new IResponseListener<UserCenterRo>() {
                @Override
                public void onResponse(UserCenterRo userCenterRo) {
                    if (userCenterRo.getResultNo() == 0) {
                        //提交成功
                        toast("委托房源成功，经纪人会第一时间联系您");
                        startActivityForResult(new Intent(getActivity(), MyHouseResourceActivity.class).putExtra(ExtraConstant.EntrustType, ""),CommonConstant.REQ_HOUSE);
                    } else {
                        //提交失败
                    }
                }

                @Override
                public void onErrorResponse(VolleyError error) {

                }
            });
        }
        if (estateStaffApi == null) {
            estateStaffApi = new EstateStaffApi(StaffDetailActivity.class, StaffListRo.class, new IResponseListener<StaffListRo>() {
                @Override
                public void onResponse(StaffListRo staffListRo) {
                    staffDo = staffListRo.getStaffDos().get(0);
                }

                @Override
                public void onErrorResponse(VolleyError error) {
                }
            });
        }
    }

    private void startRequest() {
        insertEntrustInfoRequestApi.setUserId(userdo.getUserId());
        insertEntrustInfoRequestApi.setEntrustType("出租");
        insertEntrustInfoRequestApi.setEstateName(cestName);
        insertEntrustInfoRequestApi.setCustomerMobile(userdo.getPhone());
        insertEntrustInfoRequestApi.setCustomerName(aet_entrust_rent_name.getText().toString());
        insertEntrustInfoRequestApi.setEstateCode(cestCode);
        insertEntrustInfoRequestApi.setCityCode(AppConstant.CityCode);
        insertEntrustInfoRequestApi.setRemark(aet_entrust_rent_supplement.getText().toString());
        insertEntrustInfoRequestApi.setRoomCnt(room);
        insertEntrustInfoRequestApi.setStaffNo(staffDo != null ? staffDo.getStaffNo() : "");
        insertEntrustInfoRequestApi.setStaffName(staffDo != null ? staffDo.getCnName() : "");
        insertEntrustInfoRequestApi.setStaffMobile(staffDo != null ? staffDo.getMobile() : "");
        insertEntrustInfoRequestApi.setPriceTo(aet_entrust_rent_eprice.getText().toString().equals("") ? "0" : new java.math.BigDecimal(aet_entrust_rent_eprice.getText().toString())+"");
        insertEntrustInfoRequestApi.setArea(aet_entrust_rent_area.getText().toString().equals("") ? 0 : Double.parseDouble(aet_entrust_rent_area.getText().toString()));
        insertEntrustInfoRequestApi.setStatus("待处理");
        insertEntrustInfoRequestApi.startRequest();
    }

    private void requestStaff(String cestCode){
        estateStaffApi.setEstateCode(cestCode);
        estateStaffApi.setStartindex("0");
        estateStaffApi.setPagecount("1");
        estateStaffApi.setSort("3");
        estateStaffApi.startRequest();
    }


    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (Activity.RESULT_OK == resultCode) {
            switch (requestCode) {
                case REQUSET_PHONE:
                    phone = data.getStringExtra(ExtraConstant.Phone);
                    atv_entrust_rent_phone.setText(data.getStringExtra(ExtraConstant.Phone));
                    break;
                case REQUSET_ESTATE:
                    cestName = data.getStringExtra(ExtraConstant.CestName);
                    cestCode = data.getStringExtra(ExtraConstant.CestCode);
                    atv_entrust_rent_estate.setText(data.getStringExtra(ExtraConstant.CestName));
                    requestStaff(cestCode);
                    break;
                case CommonConstant.REQ_HOUSE:
                    getActivity().finish();
                    break;
                case CommonConstant.REQ_BIND_MOBILE:
                    userInfo();
                default:
                    break;
            }
        }
    }
    private void userInfo() {
        RxDataBase.getUser()
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .compose(this.<UserDo>bindUntilEvent(FragmentEvent.DESTROY))
                .subscribe(new Action1<UserDo>() {
                    @Override
                    public void call(UserDo userDo) {
                        if (userDo != null) {
                            userdo = userDo;
                            userPhone = userDo.getPhone();
                            if (!TextUtils.isEmpty(userPhone)) {
                                atv_entrust_rent_phone.setText(userPhone);
                            }
                        }
                    }
                });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.ll_entrust_rent_estate:
                startActivityForResult(new Intent(getActivity(), EstateSearchActivity.class), REQUSET_ESTATE);
                break;
            case R.id.ll_entrust_rent_contact:
                if (AppConstant.IsLogin) {
                    if (TextUtils.isEmpty(userPhone)) {
                        startActivityForResult(new Intent(getActivity(), BindingPhoneActivity.class),
                                CommonConstant.REQ_BIND_MOBILE);
                    } else {
                        startActivityForResult(new Intent(getActivity(), ModifyPhoneActivity.class), REQUSET_PHONE);
                    }
                } else {
                    startActivityForResult(new Intent(getActivity(), BindingPhoneActivity.class),
                            CommonConstant.REQ_BIND_MOBILE);
                }
                break;
            case R.id.ll_entrust_rent_add:
                flag = !flag;
                ll_entrust_rent_extra.setVisibility(flag ? View.VISIBLE : View.GONE);
                if (flag) {
                    AnimationUtil.Rotate(img_entrust_rent_add_arrow, 300, true, 50, 0, 90);
                } else {
                    AnimationUtil.Rotate(img_entrust_rent_add_arrow, 300, true, 50, 90, 0);
                }
                break;
            case R.id.ll_entrust_rent_type:
                new AlertDialog.Builder(getContext()).setItems(type_arr,
                        new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                for (int i = 0; i < 6; i++) {
                                    if (which == i) {
                                        atv_entrust_rent_type.setText(type_arr[i]);
                                        room = i + 1;
                                    }
                                }
                            }
                        }).show();
                break;
            case R.id.bt_entrust_rent_submit:
                startRequest();
                break;
            default:
                break;
        }
    }
}